import {createConnection, Not} from "typeorm";
import {User} from "./entity/User";

createConnection().then(async (connection) => {
    // 1.全部查询所有字段
    // const userRepository = connection.getRepository(User);
    // const result = await userRepository.find();
    // console.log(result);

    // 2. 使用select 选择性的查询想要的字段
    // const userRepository = connection.getRepository(User);
    // const result = await userRepository.find({select: ['id', 'username']});
    // console.log(result);


    // // 3. 使用where 条件查询
    // const userRepository = connection.getRepository(User);
    // const result = await userRepository.find({where: {id: 2}});
    // console.log(result);


    // 4. 使用where 多条件and 查询数据
    // const userRepository = connection.getRepository(User);
    // const result = await userRepository.find({select:['id',"username"],where: {id: 4,username:"杨阳"}});
    // console.log(result);

    //5. 使用where 多条件 or 的查询
    // select * from user where user.id = 1 or user.username = 'xx';
    // const userRepository = connection.getRepository(User);
    // const result = await userRepository.find({ where: [{ id: 1 }, { username: '杨阳' }] });
    // console.log(result);

    //6. relations关系查询(前提是要先有外键关联关系)
    // select a.*,b.* from user as a left join user_extend as b on a.id = b.userId;
    // const userRepository = connection.getRepository(User);
    // const result = await userRepository.find({ relations: ['userDetail'] });
    // console.log(result);

    // // 7.使用join
    // const userRepository = connection.getRepository(User);
    // const result = await userRepository.find({
    //     join: {
    //         alias: 'user',
    //         leftJoinAndSelect: {
    //             detail: 'user.userDetail',
    //             posts: 'user.posts'
    //         }
    //     }
    // });
    // console.log(JSON.stringify(result));


    //8. order排序查询
    // select * from user order by username asc, id desc;
    // const userRepository = connection.getRepository(User);
    // const result = await userRepository.find({
    //     order: {
    //         id: 'DESC',
    //         username: 'ASC'
    //     }
    // });
    // console.log(result);


    //9. 分页查询数据
    // select * from user limit 0,10;
    // const userRepository = connection.getRepository(User);
    // const result = await userRepository.find({
    //     skip: 0,
    //     take: 10,
    // })
    // console.log(result);


    // 10. 高阶查询
    // 10.Not
    const userRepository = connection.getRepository(User);
    const result = await userRepository.find({
        username: Not('王五1')
    });
    console.log(result);
}).catch(error => console.log(error));


